<template>
    <el-row type="flex" align="middle" class="Cirypicker_wrap">
        <div class="select-panel-left">
            <span class="header-title">省份</span>
            <ul>
                <li>
                    <el-checkbox v-model="isAllSelectProvince" :indeterminate="isIndeterminate(-1)" @change="selectAll('province', $event)">全选</el-checkbox>
                </li>
                <el-checkbox-group v-model="selected.province">
                    <li v-for="province in provinces" :key="province.id">
                        <el-row type="flex" align="middle">
                        <el-checkbox class="check_none" :label="province.id" 
                        :indeterminate="isIndeterminate(province.id)"
                        @change="selectProvince('province', province.id, $event)"></el-checkbox>
                            <el-row class="check_contact" type="flex" align="middle"
                                justify="space-between">
                                <el-button @click="clickProvince(province.id)" type="text">
                                    {{province.name}}<i class="el-icon-arrow-right"></i>
                                </el-button>
                            </el-row>
                        </el-row>
                    </li>
                </el-checkbox-group>
            </ul>
        </div>
        <div class="select-panel-left">
            <span class="header-title">城市</span>
            <ul>
                <li>
                    <el-checkbox v-show="citys.length > 0" v-model="isAllSelectCity" :indeterminate="isIndeterminate(-2)" @change="selectAll('city', $event)">全选</el-checkbox>
                </li>

                <el-checkbox-group v-model="selected.city">
                    <li v-for="city in citys" :key="city.id">
                        <el-checkbox :label="city.id" @change="selectProvince('city', city.id, $event)">
                            <el-row type="flex" align="middle"
                                justify="space-between">
                                {{city.name}}</el-row>
                        </el-checkbox>
                    </li>
                </el-checkbox-group>
            </ul>
        </div>
        <i class="el-icon-d-arrow-right"></i>
        <div class="select-panel-left">
            <span class="header-title">已选
                <el-button @click="clear" style="padding: 0;" type="text">清空</el-button>
            </span>
            <ul>
                <li class="dx-selected" v-for="cityId in selected.province"
                    :key="cityId">
                    <el-row type="flex" justify="space-between" align="middle">
                        {{getCityName(cityId)}}<i @click="remove('province', cityId)" class="el-icon-close"></i>
                    </el-row>
                </li>
                <li class="dx-selected" v-for="cityId in selectedCity"
                    :key="cityId">
                    <el-row type="flex" justify="space-between" align="middle">
                        {{getCityName(cityId)}}<i @click="remove('city', cityId)" class="el-icon-close"></i>
                    </el-row>
                </li>
            </ul>
        </div>
    </el-row>
</template>

<script>
import cityJson from '@/util/city.json'
export default {
    name: 'CityPicker',
    model: {
        prop: 'inputCitys',
        event: 'change'
    },
    props: ['inputCitys'],
    mounted() {
        for (const k in cityJson) {
            const ele = cityJson[k]
            if (ele['parent'] == 0) {
                this.provinceTotal = this.provinceTotal + 1
                this.provinces.push({id: ele['id'], name: ele['name']})
            }
            // ele['checked'] = false
            this.cityData.push(ele)
        }
    },
    watch: {
        inputCitys: {
            immediate: true, // 很重要！！！
            handler () {
                // console.log('=====', val)
                if (this.inputCitys) {
                    this.inputCitys.forEach((ele) => {
                        let city = this.cityData.find((c) => {return c.id == ele})
                        if (city) {
                            if (city.parent == 0) {
                                if (this.selected.province.indexOf(ele) == -1) {
                                    this.selected.province.push(ele)
                                }
                                // 添加所有下级
                                this.cityData.forEach(e=>{
                                    if (e.parent == ele) {
                                        if (this.selected.city.findIndex(se => { return se == e.id}) == -1) {
                                            this.selected.city.push(e.id)
                                        }
                                    }
                                })
                            } else {
                                if (this.selected.city.findIndex(se => { return se == ele}) == -1) {
                                    this.selected.city.push(ele)
                                }
                            }
                        }
                    })
                }
            }
        }
    },
    data: () => ({
        provinceTotal: 0,
        cityData: [],
        provinces: [],
        selectProvinceId: 0,
        citys: [],
        selected: {
            city: [],
            province: [],
        }
    }),
    computed: {
        selectedCity: {
            get: function() {
                let citys = []
                this.selected.city.forEach((cityId) => {
                    let city = this.cityData.find((c) => {
                        return c.id == cityId
                    })
                    let idx = this.selected.province.indexOf(city.parent)
                    if (idx == -1) {
                        citys.push(cityId)
                    }
                })
                return citys
            }
        },
        isAllSelectProvince: {
            get: function() {
                return this.selected.province.length == this.provinces.length
            },
            set: function() {
                // console.log(val)
            }
        },
        isAllSelectCity: {
            get: function() {
                if (this.citys.length <= 0) {
                    return false
                }
                let isChecked = true
                this.citys.forEach(e => {
                    if (this.selected.city.indexOf(e.id) == -1) {
                        isChecked = false
                    }
                })
                return isChecked
            },
            set: function() {
                // console.log(val)
            }
        },
    },
    methods: {
        isIndeterminate(proId) {
            if (proId == -1) {
                // 省上面的全选
                return this.selected.province.length > 0 && this.selected.province.length != this.provinceTotal
            } else if(proId == -2) {
                let unchecked = false
                let checked = false
                this.citys.forEach(ele => {
                    if (this.selected.city.indexOf(ele.id) != -1) {
                        checked = true
                    } else {
                        unchecked = true
                    }
                })
                return checked && unchecked
            }
            if (this.selected.province.indexOf(proId) != -1) {
                return false
            }
            let isIn = false
            // this.cityData.forEach((ele) => {
            //     if (ele['parent'] == proId && this.selected.city.indexOf(ele.id) > -1) {
            //         isIn = true
            //     }
            // })
            let idx = this.cityData.findIndex(ele => {
                return ele['parent'] == proId && this.selected.city.indexOf(ele.id) > -1
            })
            if (idx > -1) {
                isIn = true
            }

            return isIn
        },
        selectAll(type, event) {
            if (type == 'city') {
                if (event) {
                    this.citys.forEach((ele) => {
                        if (this.selected.city.indexOf(ele.id) == -1) {
                            this.selected.city.push(ele.id)
                        }
                    })
                    
                } else {
                    this.citys.forEach((ele) => {
                        let idx = this.selected.city.indexOf(ele.id)
                        if (idx > -1) {
                            this.selected.city.splice(idx, 1)
                        }
                    })
                }
                if (this.citys.length > 0) {
                    this.check(this.citys[0], event)
                }
            } else {
                if (event) {
                    // this.$nextTick(() => {
                    this.selected.province = []
                    this.selected.city = []
                    let province = []
                    let city = []
                    
                    this.cityData.forEach((ele) => {
                        if (ele.parent == 0) {
                            province.push(ele.id)
                            // this.selected.province.push(ele.id)
                        } else {
                            // city.push(ele.id)
                            // this.selected.city.push(ele.id)
                        }
                    })
                    this.selected.province = province
                    this.selected.city = city
                    // })
                    
                } else {
                    this.selected.province = []
                    this.selected.city = []
                }
            }
            this.sendEvent()
        },
        getCity( cityId ) {
            let city = this.cityData.find((ele) => {
                return ele['id'] == cityId
            })
            return city
        },
        getCityName( cityId ) {
            let city = this.getCity(cityId)
            return city['name']
        },
        reloadCitys() {
            // 查询下级所有信息
            this.citys = []
            let citys = this.cityData.filter((ele) => {
                return ele.parent == this.selectProvinceId
            })
            // citys.forEach((ele) => {
            //     if (ele.checked) {
            //         this.selected.city.push(ele.id)
            //     }
            // })
            this.citys = citys
        },
        clickProvince(proId) {
            this.selectProvinceId = proId
            this.reloadCitys()
        },
        selectProvince(type, clickId, event) {
            // console.log(type, clickId, event)
            if (type == 'province') {
                // 将省添加到选中
                // let province = this.getCity(clickId)
                if (event) {
                    this.cityData.forEach((ele) => {
                        if (ele.parent == clickId) {
                            if (this.selected.city.indexOf(ele.id) == -1) {
                                this.selected.city.push(ele.id)
                            }
                        }
                    })
                } else {
                    this.cityData.forEach((ele) => {
                        if (ele.parent == clickId) {
                            let idx = this.selected.city.indexOf(ele.id)
                            if (idx > -1) {
                                this.selected.city.splice(idx, 1)
                            }
                        }
                    })
                }
            } else if(type == 'city') {
                // 市级
                let city = this.getCity(clickId)
                // 选中时，检查整个省级下的市是不是都选择了，如果是，改选中为省级，清除市级数据
                this.check(city, event)
                
            } else {
                // this.citys = []

                // for (const k in cityJson) {
                //     const ele = cityJson[k];
                //     if (ele['parent'] == clickId) {
                //         this.citys.push({id: ele['id'], name: ele['name']})
                //     }
                // }
            }
            this.sendEvent()
        },
        check(city, event) {
            if (event) {
                let isSelectProvince = true
                this.cityData.forEach((ele) => {
                    if (ele.parent == city.parent && this.selected.city.indexOf(ele.id) == -1) {
                        isSelectProvince = false
                    }
                })
                if (isSelectProvince) {
                    let idx = this.cityData.findIndex((ele)=> {
                        return ele.id == city.parent
                    })
                    // this.cityData[idx].checked = true
                    if (this.selected.province.indexOf(this.cityData[idx].id) == -1) {
                        this.selected.province.push(this.cityData[idx].id)
                    }
                }
            } else {
                // 取消选中时，检查省级，如果省选中要去掉换为市级单位
                let idx = this.selected.province.indexOf(city.parent)
                if (idx > -1) {
                    this.selected.province.splice(idx , 1)
                }
            }
        },
        sendEvent() {
            let ids = []
            this.selected.province.forEach(e=> {
                ids.push(e)
            })
            this.selected.city.forEach(e => {
                let city = this.getCity(e)
                if (ids.indexOf(city.parent) == -1) {
                    ids.push(e)
                }
            })
            this.$emit('change', ids)
        },
        clear() {
            this.selected.province = []
            this.selected.city = []
            this.sendEvent()
        },
        remove(type, id) {
            if (type == 'province') {
                let idx = this.selected.province.indexOf(id)
                this.selected.province.splice(idx, 1)
                // 删除下面的所有城市
                var arr = this.selected.city.filter((cityId) => {
                    let city = this.cityData.find((c) => {
                        return c.id == cityId
                    })
                    return id != city.parent;
                });
                this.selected.city = arr
            } else if (type == 'city') {
                let idx = this.selected.city.indexOf(id)
                this.selected.city.splice(idx, 1)
            }
            this.sendEvent()
        }
    }
}
</script>

<style>
.Cirypicker_wrap .select-panel-left {
    width: 200px;
    background-color: #fff;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    overflow: hidden;
    margin: 15px 10px 0 0;
}

.Cirypicker_wrap .select-panel-left .header-title {
    border-bottom: 1px solid #e0e0e0;
    background-color: #fafafa;
    color: #333;
    font-size: 14px;
    line-height: 22px;
    padding: 8px 12px;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-pack: justify;
    -ms-flex-pack: justify;
    justify-content: space-between;
}
.Cirypicker_wrap .select-panel-left ul {
    height: 192px;
    padding: 6px 0;
    overflow-y: auto;
    position: relative;
}

.Cirypicker_wrap .select-panel-left ul li {
    padding: 6px 12px;
    position: relative;
    cursor: pointer;
    line-height: initial;
    text-align: left;
}

.Cirypicker_wrap .select-panel-left ul li:hover {
    background: #f0f0f0;
}

.Cirypicker_wrap .select-panel-left .check_contact {
    width: 100%;
    font-size: 14px;
}

.Cirypicker_wrap .select-panel-left .check_contact .el-button {
    width: 100%;
    padding: 0;
    color: #606266;
}

.Cirypicker_wrap .select-panel-left .check_contact .el-button span {
    width: 100%;
    text-indent: 8px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.Cirypicker_wrap .select-panel-left .check_none .el-checkbox__label {
    display: none;
}
.Cirypicker_wrap .el-icon-d-arrow-right {
    color: #409EFF;
    margin-right: 10px;
    font-size: 16px;
}
.Cirypicker_wrap .select-panel-left ul li.dx-selected {
    margin: 8px 12px;
    padding: 2px 8px;
    background-color: #f0f0f0;
    border-radius: 4px;
    position: relative;
    font-size: 14px;
}
</style>